package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
@EnableCaching
//为了简化，省略service
public class UserController {

    @Autowired
    private UserMapper userMapper;
    /* *
     * @Author: lidong
     * @Date: 2025/3/6 13:31
     * @Description: 新增
     */
    @PostMapping
//    @CachePut(value = "user", key = "#user.id") //user是方法的参数
    @CachePut(value = "user", key = "#result.id") //result是方法的返回值
//    @CachePut(value = "user", key = "#p0.id") //p0是方法的第一个参数
//    @CachePut(value = "user", key = "#a0.id") //a0是方法的第一个参数
    //设置缓存
    //redis key :user::xxx
    //redis value :User对象序列化后的json
    public User save(@RequestBody User user) {

        userMapper.insert(user);
        return user;
    }

    /* *
     * @Author: lidong
     * @Date: 2025/3/6 13:32
     * @Description: 查询
     */
    @GetMapping
    @Cacheable(value = "user", key = "#id")
    //获取缓存，如果缓存中没有，就执行方法，并将结果存入缓存
    // 如果缓存中有，就直接返回缓存中的数据
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

    /* *
     * @Author: lidong
     * @Date: 2025/3/6 13:32
     * @Description: 单删
     */
    @DeleteMapping
    @CacheEvict(value = "user", key = "#id")
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

    /* *
     * @Author: lidong
     * @Date: 2025/3/6 13:32
     * @Description: 批量删除
     */
    @DeleteMapping("/delAll")
    @CacheEvict(value = "user", allEntries = true)
    public void deleteAll(){
        userMapper.deleteAll();
    }

}
